'''
Created on Oct 30, 2009

@author: Owner
'''
import sys
import optparse
import os
ROOT_PATH = "../../../"
sys.path.append("../../../")

import game
import game_controller
import anch_tournament

MAX_EXPAND = game.MAX_EXPAND
USAGE_STRING = game.USAGE_STRING

trainerMod = None
anch_tournamentMod = None


class AnchTournamentTrainer(object):
	'''
	classdocs
	'''

	trainer_id = -1
	
	def __init__(self):
		'''
		Constructor
		'''
		
	@staticmethod 
	def start_game(args, opts, fn, order = 0):
		global trainerMod, anch_tournamentMod
				
		gm = AnchTournamentTrainer.construct_controller(args[0], args[1],\
			opts.maxExpand, fn, order)
		times = opts.times
		while times > 0:
			gm.reset()
			winner = gm.play_game()
			print("winner:{0}".format(winner))
			
			anch_tournamentMod = trainerMod.mT
			
			anch_tournamentMod.AnchTournamentPlayer.updateDatabase(\
					winner == AnchTournamentTrainer.trainer_id)
			
			print("strategy_hit:{0}".format(anch_tournamentMod.AnchTournamentPlayer.getCounter()))
			anch_tournamentMod.AnchTournamentPlayer.resetCounter()
			
			times-=1
		
		
	@staticmethod
	def construct_controller(gameName, playerName, maxExpansions, fn, order):
		global trainerMod
		wd = os.getcwd()
		
		# Load game, player modules
		gameMod = game.load_module(gameName.lower(), None, wd)
		path_player_lobby = os.path.join(ROOT_PATH, game.PLAYER_PATH, gameName.lower())
		playerMod = game.load_module(playerName, path_player_lobby, wd)
		trainerMod = game.load_module('anch', path_player_lobby, wd)
		
		#set the switch
		trainerMod._traning_mode = True
		
		if gameMod == None or playerMod == None:
			sys.exit(2)
		
		# Load game, player classes
		state = game.class_instance(gameMod, gameName+game.GAME_SUFFIX)
		if state == None:
			sys.exit(2)
			
		gameIDs = state.get_players()
		
		trainer_name = 'anch_trainer'
		
		if order == 0:
			p1 = game.class_instance(trainerMod, gameName+game.PLAYER_SUFFIX, 
						trainer_name, gameIDs[0])
			p2 = game.class_instance(playerMod, gameName+game.PLAYER_SUFFIX, 
						playerName, gameIDs[1])
			fn = [game_controller.GameController.TOURN, fn]
			AnchTournamentTrainer.trainer_id = gameIDs[0]
		else:
			p1 = game.class_instance(playerMod, gameName+game.PLAYER_SUFFIX, 
						playerName, gameIDs[0])
			p2 = game.class_instance(trainerMod, gameName+game.PLAYER_SUFFIX, 
						trainer_name, gameIDs[1])
			fn = [fn, game_controller.GameController.TOURN]
			AnchTournamentTrainer.trainer_id = gameIDs[1]
		
		if p1 == None or p2 == None:
			print("There needs two players to attend the match")
			sys.exit(2)
			
		try:
			gm = game_controller.GameController(state, [p1,p2], fn, \
			maxExpansions, wd)
		except game_controller.PlayerException, e:
			print "Player ID not covered!"
			print e
			sys.exit(3)	
			
		return gm
	
def main():
	
	parser = optparse.OptionParser()
	
	# Set up our option parser
	parser.set_usage(USAGE_STRING)
	parser.add_option("--a", "--alpha-beta", action="store_true", dest="alphabeta",
		help="Have player 1 use alpha-beta tree search (default).")
	parser.add_option("--m", "--minmax", action="store_true", dest="minimax",
		help="Have player 1 use minmax tree search.")
	parser.add_option("--t", "--tournament", action="store_true", dest="tournament",
		help="Have player 2 use minimax tree search (default).")
	parser.add_option("-e", "--max-expand", type="int", dest="maxExpand",
		help="Set the maximum number of expansions per ply (default=%d)" \
			% MAX_EXPAND, metavar="MAX_EXPAND")
	parser.add_option("--tm", "--times", type="int", dest="times",
		help="Set practice times (default=1)", metavar="TIMES")
	parser.add_option("-x", "--exclude", action="append", dest="exclusions",
		help="Exclude a player from the tournament.  Use multiple --exclude " \
		"to exclude many players.", metavar="PLAYER")
	parser.add_option("-v", "--verbose", action="store_false", dest="quiet",
		help="Print out all the game states in tournament mode.")
	parser.set_defaults(alphabeta=False, minimax=False, tournament=False,
		maxExpand=MAX_EXPAND, exclusions=[], quiet=True, times=1)
	
	# Parse the arguments
	opts, args = parser.parse_args()
	
	i = 0
	fn = None
	if opts.alphabeta: 
		i+=1
		fn = game_controller.GameController.ALPHA_BETA
	if opts.minimax:
		i+=1
		fn = game_controller.GameController.MINIMAX
	if opts.tournament: 
		i+=1
		fn = game_controller.GameController.TOURN
		
	if i > 1:
		print "Error: --alpha-beta, --minmax and --tournament are mutually exclusive."
		sys.exit(1)
		
	if fn == None:
		fn = game_controller.GameController.MINIMAX
	
	if len(args) != 2:
			print "Anch Tournament Trainer requires 2 argument.  "\
					"Use '-h' for more information."
			sys.exit(1)
			
	AnchTournamentTrainer.start_game(args, opts, fn)
	
	pass

if __name__ == "__main__":
	main()

		